package com.kami.service.impl;

import java.util.List;

import javax.annotation.PostConstruct;

import org.apache.commons.lang.StringUtils;
import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.kami.dao.ScheduleJobMapper;
import com.kami.entity.ScheduleJob;
import com.kami.entity.ScheduleJobExample;
import com.kami.service.ScheduleJobService;
import com.kami.utils.ScheduleUtils;

@Service
public class ScheduleJobServiceImpl implements ScheduleJobService{

	@Autowired
    private Scheduler scheduler;
	@Autowired
	private ScheduleJobMapper scheduleJobMapper;

	@PostConstruct
	public void init(){
		List<ScheduleJob> list = scheduleJobMapper.selectByExample(null);
		for (ScheduleJob scheduleJob : list) {
			CronTrigger cronTrigger = ScheduleUtils.getCronTrigger(scheduler, scheduleJob.getJobId());
			if (null == cronTrigger)
			{
				ScheduleUtils.createScheduleJob(scheduler, scheduleJob);
			}else
			{
				ScheduleUtils.updateScheduleJob(scheduler, scheduleJob);
			}
		}
	}
	
	@Override
	public List<ScheduleJob> findByJob(ScheduleJob job) {
		String beanName = job.getBeanName();
		ScheduleJobExample example = new ScheduleJobExample();
		if (StringUtils.isNotEmpty(beanName)) {
			example.createCriteria().andBeanNameLike("%"+job+"%");
		}
		return scheduleJobMapper.selectByExample(example);
	}

	@Override
	public void run(Long jobId) {
		ScheduleUtils.run(scheduler, findById(jobId));
	}
	
	public ScheduleJob findById(Long id){
		return scheduleJobMapper.selectByPrimaryKey(id);
	}
}
